package com.ityuwen.mengyagushi.order.service.template;

import com.alibaba.fastjson.JSON;
import com.ityuwen.mengyagushi.common.constant.RedisConstant;
import com.ityuwen.mengyagushi.common.constant.SystemConstant;
import com.ityuwen.mengyagushi.order.helper.SignHelper;
import com.ityuwen.mengyagushi.vo.order.OrderInfoVo;
import com.ityuwen.mengyagushi.vo.order.TradeVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

public abstract class OrderConfirm {

    private RedisTemplate redisTemplate;

    public OrderConfirm() {
    }

    public OrderConfirm(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public OrderInfoVo trade(TradeVo tradeVo) {

        OrderInfoVo orderInfoVo = new OrderInfoVo();

        // 防重复提交的唯一标识：任何订单都需要防止重复提交
        String tradeNo = IdWorker.getIdStr();
        orderInfoVo.setTradeNo(tradeNo);
        this.redisTemplate.opsForValue().set(RedisConstant.ORDER_IDEM_PREFIX + tradeNo, tradeNo, 24, TimeUnit.HOURS);

        // 支付方式
        orderInfoVo.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN);

        // 订单类型
        orderInfoVo.setItemType(tradeVo.getItemType());

        // 特定步骤
        confirm(tradeVo, orderInfoVo);

        // 时间戳和签名
        orderInfoVo.setTimestamp(SignHelper.getTimestamp());
        orderInfoVo.setSign(SignHelper.getSign(JSON.parseObject(JSON.toJSONString(orderInfoVo), HashMap.class)));

        return orderInfoVo;
    }

    public abstract void confirm(TradeVo tradeVo, OrderInfoVo orderInfoVo);
}
